package com.spring.picture.aop;

import com.spring.picture.annotation.AuthCheck;
import com.spring.picture.exception.BusinessException;
import com.spring.picture.exception.ErrorCode;
import com.spring.picture.model.entity.User;
import com.spring.picture.model.enums.UserRoleEnum;
import com.spring.picture.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();

        /*
          这段代码的作用是从当前线程中获取与当前请求相关的 HttpServletRequest 对象。它通常用于在非控制器类（如 Service 或工具类）中获取当前 HTTP 请求的信息
          RequestContextHolder 是基于 ThreadLocal 实现的
         */
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);

        // 不需要权限，放行
        if (mustRoleEnum == null) {
            /*
              调用 joinPoint.proceed() 会继续执行被拦截的目标方法
              proceed() 的返回值是目标方法的执行结果
             */
            return joinPoint.proceed();
        }

        // 获取当前用户具有的权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        // 没有权限，拒绝
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 要求 必须具有管理员权限，但用户没有管理员权限，拒绝
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        // 通过权限，放行
        return joinPoint.proceed();
    }
}
